/*
 * Copyright (C) 2011 Terence Lin
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */

package com.example.android.chickylander;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.IBinder;
import android.widget.Toast;

/*
 * This class provides back ground music service to the app
 */
public class MusicService extends Service implements MediaPlayer.OnErrorListener {

	private final IBinder mBinder = new ServiceBinder();
	MediaPlayer mPlayer;
	private int len = 0;
	
	public MusicService(){}
	
	public class ServiceBinder extends Binder {
		MusicService getService(){
			return MusicService.this;
		}
	}
	
	@Override
	public IBinder onBind(Intent arg0) {
		return mBinder;
	}
	
	public void onCreate(){
		super.onCreate();
		mPlayer = MediaPlayer.create(this, R.raw.bgm);
		mPlayer.setOnErrorListener(this);
		
		if (mPlayer != null){
			mPlayer.setLooping(true);
			mPlayer.setVolume(50, 50);
		}
	}
	
	public void onDestroy(){
		super.onDestroy();
		if (mPlayer != null){
			try{
				mPlayer.stop();
				mPlayer.release();
			} finally{
				mPlayer = null;
			}		
			
		}
	}

	public int onStartCommand(){
		mPlayer.start();
		return START_STICKY;
	}
	
	public void pauseMusic(){
		if (mPlayer.isPlaying()){
			mPlayer.pause();
			len = mPlayer.getCurrentPosition();
		}
	}
	
	public void resumeMusic(){
		if (!mPlayer.isPlaying()){
			mPlayer.seekTo(len);
			mPlayer.start();
		}
	}
	
	public void resetMusic(){
		if (mPlayer.isPlaying()){
			mPlayer.pause();
			len = 0;
		}
	}
	
	public void stopMusic(){	
		mPlayer.stop();
		//mPlayer.release();
		//mPlayer = null;
	}
	
	public boolean onError(MediaPlayer mp, int what, int extra) {
		Toast.makeText(this, "Error with Music Player", Toast.LENGTH_SHORT).show();
		if (mPlayer != null){
			try{
				mPlayer.stop();
				mPlayer.release();
			} finally{
				mPlayer = null;
			}		
			
		}
		return false;
	}

}
